package user

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/user"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

// 用户地址列表
func GetAddrListByUserId(userID int64) ([]formdata.AddrInfo, error) {
	u := user.UserAddress{
		UserID: userID,
	}
	return u.GetAddrListByUserId()
}

// 创建用户地址
func CreateAddr(data formdata.CreateUserAddr, userID int64) error {
	fmt.Println("CreateAddr", userID)
	isDefault, _ := strconv.Atoi(data.IsDefault)
	u := user.UserAddress{
		UserID:    userID,
		Name:      data.Name,
		Phone:     data.Phone,
		Province:  data.Province,
		City:      data.City,
		District:  data.District,
		Address:   data.Address,
		IsDefault: int8(isDefault),
	}
	return u.CreateAddr()
}

// 地址详情
func DetailAddr(data formdata.UpdateAddr, userID int64) (info formdata.AddrInfo, err error) {
	addrId, _ := strconv.Atoi(data.AddrID)
	addr := user.UserAddress{
		Model:  gorm.Model{ID: uint(addrId)},
		UserID: userID,
	}
	addrInfo, err := addr.GetAddrByAddrId()
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return formdata.AddrInfo{}, nil
		}
		return formdata.AddrInfo{}, err
	}
	info = formdata.AddrInfo{
		ID:        int64(addrInfo.ID),
		UserID:    addrInfo.UserID,
		Name:      addrInfo.Name,
		Phone:     addrInfo.Phone,
		Province:  addrInfo.Province,
		City:      addrInfo.City,
		District:  addrInfo.District,
		Address:   addrInfo.Address,
		IsDefault: addrInfo.IsDefault,
	}
	return info, nil
}

const (
	IsDefault = 1
)

// 查询默认用户地址
func GetAddrDefault(userID int64) (formdata.AddrInfo, error) {
	u := user.UserAddress{
		UserID:    userID,
		IsDefault: IsDefault,
	}
	return u.GetAddrDefault()
}
